class Admin::ShopsController < AdminController
  def index
    @shops = Shop.all
    if not params[:province_id].blank?
      @shops = @shops.where(province_id: params[:province_id])
      if not params[:city_id].blank?
        @shops = @shops.where(city_id: params[:city_id])
        if not params[:district_id].blank?
          @shops = @shops.where(district_id: params[:district_id])
        end
      end
    end
    if not params[:name].blank?
      @shops = @shops.where("name LIKE ?", "%#{params[:name]}%")
    end
    if params[:state].presence
      @shops = @shops.where(state: params[:state])
    end
    if params[:direct_sale].presence
      @shops = @shops.where(direct_sale: ActiveModel::Type::Boolean.new.cast(params[:direct_sale]))
    end
    @shops = @shops.order("created_at DESC").page(params[:page]).per(params[:per])
  end

  def show
    @shop = Shop.find params[:id]
  end
  

  def new
    @shop = Shop.new
  end

  def create
    @shop = Shop.new shop_params
    if @shop.save
      redirect_to admin_shops_path, notice: "保存成功！"
    else
      render :new
    end
  end

  def edit
    @shop = Shop.find params[:id]
  end

  def update
    @shop = Shop.find params[:id]
    if @shop.update shop_params
      redirect_to admin_shops_path, notice: "更新成功！"
    else
      render :edit
    end
  end
  
  def destroy
    @shop = Shop.find params[:id]
    if @shop.destroy
      redirect_to admin_shops_path, notice: "删除成功."
    else
      redirect_to admin_shops_path, notice: "删除失败."
    end
  end

  def reporter
    @shop = Shop.find params[:id]
    @orders = @shop.orders.where(state: :completed)
    if params[:begin_at].presence && params[:end_at].presence
      @begin_at = params[:begin_at].to_date
      @end_at = params[:end_at].to_date
    else
      @begin_at = Time.now.to_date
      @end_at = Time.now.to_date
    end
    @orders = @orders.between_times(@begin_at.beginning_of_day, @end_at.end_of_day).order("created_at DESC")
    if params[:download].presence && params[:download]
      
    end
  end
  

  private

  def shop_params
    params.require(:shop).permit(:name, :phone, :avatar, :direct_sale, :big_avatar, :state, :sales_percent, :level, :idcard_front, :idcard_back, :license, :province_id, :city_id, :district_id, :address, :shop_type_id, :bank, :bank_account, :bank_account_name, :business_range)
  end
end
